package com.div.tools.toast

import android.content.Context
import android.content.res.Resources
import android.graphics.Color
import android.graphics.drawable.Drawable
import android.graphics.drawable.GradientDrawable
import android.util.TypedValue
import android.view.Gravity
import android.widget.TextView
import android.widget.Toast

class ToastTool {
    companion object {

        fun showLong(context: Context, resId: Int) {
            showLong(context, Resources.getSystem().getString(resId))
        }

        fun showLong(context: Context, text: String) {
            if (text.isEmpty()) return
            makeToast(context, text, Toast.LENGTH_LONG).show()
        }

        fun showShort(context: Context, resId: Int) {
            showShort(context, Resources.getSystem().getString(resId))
        }

        fun showShort(context: Context, text: String) {
            if (text.isEmpty()) return
            makeToast(context, text, Toast.LENGTH_SHORT).show()
        }

        private fun makeToast(context: Context, text: String, duration: Int): Toast {
            val toast = Toast(context)
            val tvToast = TextView(context)
            val padding = dp2px(16F).toInt()
            tvToast.setPadding(padding, padding, padding, padding)
            tvToast.background = createBg(context)
            tvToast.gravity = Gravity.START
            tvToast.setTextColor(Color.WHITE)
            tvToast.text = text
            toast.setGravity(Gravity.CENTER, 0, 0)
            toast.duration = duration
            toast.view = tvToast

            return toast
        }

        private fun createBg(context: Context): Drawable {
            val drawable = GradientDrawable()
            drawable.setColor(Color.parseColor("#2E2E41"))
            drawable.cornerRadius = dp2px(6F)
            return drawable
        }

        private fun dp2px(dp: Float): Float {
            return (TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp, Resources.getSystem().displayMetrics) + 0.5F)
        }
    }
}